package com.kaikeba.wx.controller;

import com.kaikeba.bean.BootStrapTableExpress;
import com.kaikeba.bean.Express;
import com.kaikeba.bean.Message;
import com.kaikeba.bean.User;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.ExpressService;
import com.kaikeba.util.DateFormatUtil;
import com.kaikeba.util.JSONUtil;
import com.kaikeba.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @description:
 * @author: ManolinCoder
 * @time: 2021/9/6
 */
public class ExpressController {
    @ResponseBody("/wx/findExpressByUserPhone.do")
    public String findByUserPhone(HttpServletRequest request, HttpServletResponse response){
        User wxUser = UserUtil.getWxUser(request.getSession());
        String userPhone = wxUser.getuPhoneNumber();
        List<Express> list = ExpressService.findByUserPhone(userPhone);
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        //将Express类型的数据集合转换为BootStrapTableExpress类型的数据集合,对时间状态等数据进行处理，便于用户理解
        if (list.size() != 0){
            for (Express e : list) {
                String inTime = DateFormatUtil.format(e.getInTime());
                String outTime = e.getOutTime()==null?"未出库":DateFormatUtil.format(e.getOutTime());
                String status = e.getStatus()==0?"待取件":"已取件";
                String code = e.getCode()==null?"已取件":e.getCode();
                BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
                list2.add(e2);
            }
        }

        Message msg = new Message();
        if (list.size()==0){
            msg.setStatus(-1);
        }else {
            msg.setStatus(0);
            //对list集合进行流操作中的过滤操作，相当于遍历list集合中的每一个Express对象。流不会改变原本数据
            Stream<BootStrapTableExpress> status0Express = list2.stream().filter(express -> {//得到快递的status为0的全部快递
                if (express.getStatus().equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time-o2Time);//为正数则o1大，为0相等，为负数则o2大
            });
            Stream<BootStrapTableExpress> status1Express = list2.stream().filter(express -> {//得到快递的status为1的全部快递
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time-o2Time);//为正数则o1大，为0相等，为负数则o2大
            });
            Object[] s0 = status0Express.toArray();//获取流操作完毕的数据
            Object[] s1 = status1Express.toArray();//获取流操作完毕的数据
            Map data = new HashMap();
            data.put("status0",s0);
            data.put("status1",s1);
            msg.setData(data);
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/findByNumberAndPhone.do")
    public String findByNumberAndPhone(HttpServletRequest request, HttpServletResponse response){
        String expressNum = request.getParameter("expressNum");
        User wxUser = UserUtil.getWxUser(request.getSession());
        BootStrapTableExpress returnExpress = null;
        Message msg = new Message();
        if (wxUser.isUser()){
            //是用户，通过快递的number和userPhone查,属于该用户的才查出来
            Express express = ExpressService.findByNumberAndPhone(expressNum, wxUser.getuPhoneNumber(), null);
            if (express != null){
                String inTime = DateFormatUtil.format(express.getInTime());
                String outTime = express.getOutTime()==null?"未出库":DateFormatUtil.format(express.getOutTime());
                String status = express.getStatus()==0?"待取件":"已取件";
                String code = express.getCode()==null?"已取件":express.getCode();
                returnExpress = new BootStrapTableExpress(express.getId(),express.getNumber(),express.getUsername(),express.getUserPhone(),express.getCompany(),code,inTime,outTime,status,express.getSysPhone());
                if (express.getStatus() == 0){
                    msg.setStatus(0);
                }else {
                    msg.setStatus(1);
                }
                msg.setData(returnExpress);
                msg.setResult("查询成功!");
            }else {
                msg.setStatus(-1);
                msg.setResult("快递不存在!");
            }
        }else {
            //是快递员，通过快递的number和sysPhone查，属于该快递员派送的才查出来(不能取)
            //快递员自身的快递也可以查出来(可以取)，比较userPhone和当前登录的快递员的手机号
            //首先查询快递员个人快递
            Express personalExpress = ExpressService.findByNumberAndPhone(expressNum,wxUser.getuPhoneNumber(),null);
            if (personalExpress != null){
                String inTime = DateFormatUtil.format(personalExpress.getInTime());
                String outTime = personalExpress.getOutTime()==null?"未出库":DateFormatUtil.format(personalExpress.getOutTime());
                String status = personalExpress.getStatus()==0?"待取件":"已取件";
                String code = personalExpress.getCode()==null?"已取件":personalExpress.getCode();
                returnExpress = new BootStrapTableExpress(personalExpress.getId(),personalExpress.getNumber(),personalExpress.getUsername(),personalExpress.getUserPhone(),personalExpress.getCompany(),code,inTime,outTime,status,personalExpress.getSysPhone());
                if (personalExpress.getStatus() == 0){
                    msg.setStatus(0);
                }else {
                    msg.setStatus(1);
                }
                msg.setData(returnExpress);
                msg.setResult("查询成功!");
            }else {
                //不是个人快递，查询是否是派送的快递
                Express sendExpress = ExpressService.findByNumberAndPhone(expressNum,null,wxUser.getuPhoneNumber());
                if (sendExpress != null){
                    String inTime = DateFormatUtil.format(sendExpress.getInTime());
                    String outTime = sendExpress.getOutTime()==null?"未出库":DateFormatUtil.format(sendExpress.getOutTime());
                    String status = sendExpress.getStatus()==0?"待取件":"已取件";
                    String code = sendExpress.getCode()==null?"已取件":sendExpress.getCode();
                    returnExpress = new BootStrapTableExpress(sendExpress.getId(),sendExpress.getNumber(),sendExpress.getUsername(),sendExpress.getUserPhone(),sendExpress.getCompany(),code,inTime,outTime,status,sendExpress.getSysPhone());
                    if (sendExpress.getStatus() == 0){
                        msg.setStatus(2);
                    }else {
                        msg.setStatus(1);
                    }
                    msg.setData(returnExpress);
                    msg.setResult("查询成功!");
                }else {
                    //都不是则没有查到
                    msg.setStatus(-1);
                    msg.setResult("快递不存在!");
                }
            }
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/userExpressList.do")
    public String expressList(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        //查询当前用户所有的未取快递
        List<Express> list = ExpressService.findByUserPhoneAndStatus(userPhone,0);
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        //将Express类型的数据集合转换为BootStrapTableExpress类型的数据集合,对时间状态等数据进行处理，便于用户理解
        if (list.size() != 0){
            for (Express e : list) {
                String inTime = DateFormatUtil.format(e.getInTime());
                String outTime = e.getOutTime()==null?"未出库":DateFormatUtil.format(e.getOutTime());
                String status = e.getStatus()==0?"待取件":"已取件";
                String code = e.getCode()==null?"已取件":e.getCode();
                BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
                list2.add(e2);
            }
        }
        Message msg = new Message();
        if (list.size() == 0){
            msg.setStatus(-1);
            msg.setResult("未查询到快递");
        }else {
            msg.setStatus(0);
            msg.setResult("查询成功");
            msg.setData(list2);
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("name");
        String userPhone = request.getParameter("phone");

        //这个对象构造方法的sysPhone参数是根据当前登录用户从session中获取的
        Express e = new Express(number,username,userPhone,company,UserUtil.getWxUser(request.getSession()).getuPhoneNumber());
        boolean flag = ExpressService.insert(e);
        Message msg = new Message();
        if (flag){
            //录入成功
            msg.setStatus(0);
            msg.setResult("快递录入成功!");
        }else {
            //录入失败
            msg.setStatus(-1);
            msg.setResult("快递录入失败!");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
}
